package com.gitee.kamismile.gatewayAgent.server.handler;

import com.gitee.kamismile.gatewayAgent.protobuf.Message;
import com.gitee.kamismile.gatewayAgent.server.bootstrap.GatewayAgentConstant;
import com.gitee.kamismile.stone.commmon.util.SnowflakeIdWorker;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import java.util.concurrent.TimeUnit;

/**
 * Created by lidong on 2017/2/8.
 */
@ConditionalOnMissingBean(GateWayServerInitializer.class)
public class GateWayServerInitializer extends ChannelInitializer<SocketChannel> {
    private SslContext sslCtx;
    private SnowflakeIdWorker snowflakeIdWorker;
    private GatewayAgentConstant gatewayAgentConstant;

    public void setSslCtx(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    public void setSnowflakeIdWorker(SnowflakeIdWorker snowflakeIdWorker) {
        this.snowflakeIdWorker = snowflakeIdWorker;
    }

    public void setGatewayAgentConstant(GatewayAgentConstant gatewayAgentConstant) {
        this.gatewayAgentConstant = gatewayAgentConstant;
    }

    public SnowflakeIdWorker getSnowflakeIdWorker() {
        return snowflakeIdWorker;
    }

    public GatewayAgentConstant getGatewayAgentConstant() {
        return gatewayAgentConstant;
    }

    /**
     * 只会一个实例
     *
     * @param ch
     */
    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        if (sslCtx != null) {
            p.addLast(sslCtx.newHandler(ch.alloc()));
        }

        p.addLast(new ProtobufVarint32FrameDecoder());
        p.addLast(new ProtobufDecoder(Message.RouterMessage.getDefaultInstance()));

        p.addLast(new ProtobufVarint32LengthFieldPrepender());
        p.addLast(new ProtobufEncoder());

        p.addLast(new IdleStateHandler(0, 0, 100, TimeUnit.SECONDS));
        p.addLast(new HeartBeatHandler(gatewayAgentConstant));

        GateWayServerHandler gateWayServerHandler = new GateWayServerHandler();
        gateWayServerHandler.setGatewayAgentConstant(gatewayAgentConstant);
        gateWayServerHandler.setSnowflakeIdWorker(snowflakeIdWorker);
        p.addLast(gateWayServerHandler);

    }
}
